package net.rock.controller;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import net.rock.pojo.Cart;
import net.rock.pojo.User;
import net.rock.service.CartService;
import net.rock.utils.ServiceCaller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@EqualsAndHashCode
@ToString
@Getter
@Setter
class CartResult {
    private int id;
    private int userId;
    private int cnt;

    public CartResult(){}

    public CartResult(int id, int userId, int cnt) {
        this.id = id;
        this.userId = userId;
        this.cnt = cnt;
    }

    public Cart toCart() {
        return new Cart(id, userId, cnt);
    }

    public static CartResult fromCart(Cart cart) {
        return new CartResult(cart.getBookId(), cart.getUserId(), cart.getCnt());
    }
}

@RestController
@RequestMapping("/api/cart")
public class CartController {
    @Autowired
    private CartService cartService;

    @Autowired
    private ServiceCaller serviceCaller;

    @GetMapping("/show")
    public List<CartResult> fetchCarts(
            @CookieValue(value = "sessionID", defaultValue = "") String sessionId
    ) {
        User user = serviceCaller.fetchUserBySessionId(sessionId);
        return cartService.fetchCarts(user.getId()).stream().map(CartResult::fromCart).collect(Collectors.toList());
    }

    @PostMapping("/add")
    public void add(
            @CookieValue(value = "sessionID", defaultValue = "") String sessionId,
            @RequestBody CartResult cart
    ) {
        User user = serviceCaller.fetchUserBySessionId(sessionId);
        cart.setUserId(user.getId());
        cartService.add(cart.toCart());
    }

    @PostMapping("/edit")
    public void edit(
            @CookieValue(value = "sessionID", defaultValue = "") String sessionId,
            @RequestBody CartResult cart
    ) {
        User user = serviceCaller.fetchUserBySessionId(sessionId);
        cart.setUserId(user.getId());
        cartService.edit(cart.toCart());
    }

    @PostMapping("/del")
    public void del(
            @CookieValue(value = "sessionID", defaultValue = "") String sessionId,
            @RequestBody CartResult cart
    ) {
        User user = serviceCaller.fetchUserBySessionId(sessionId);
        cartService.del(user.getId(), cart.getId());
    }
}